const SECRET_ACCESS_KEY = '901394ea9dd148518726d199830632be';
import axios from 'axios';
import moment from 'moment';
import { User } from '../entities/user/user';
import { TrainingInRotation } from '../entities/user/trainingInRotation';

// 定义一个获取二维码URL的请求接口
import { Service } from 'egg';
export default class Login extends Service {

  public async login() {
    const res = await axios.get(`https://server01.vicy.cn/8lXdSX7FSMykbl9nFDWESdc6zfouSAEz/wxLogin/tempUserId?secretKey=${SECRET_ACCESS_KEY}`);
    if (res.data.errcode === 0) {
      return { code: 0, data: res.data.data };
    }
  }

  public async loginCallBack(ctx) {
    /* 接收微信账户信息接口 */
    /* 获取微信的用户信息 */

    this.addUser(ctx); // 存入数据库
    // this.app.redis.set(ctx.request.body.tempUserId, JSON.stringify(ctx.request.body));
    // this.app.redis.expire(ctx.request.body.tempUserId, 10);

    // 存入轮训模型
    const userInfo = ctx.request.body;

    const newObj = TrainingInRotation.transformerThis(userInfo);
    const validateArr = await newObj.validatorClass(false);

    if (validateArr.length !== 0) {
      return validateArr;
    }

    await ctx.model.TrainingInRotation.create(userInfo);

    const timer = setTimeout(async () => {
      // 清除马上登陆返回的信息在轮训模型库中
      await ctx.model.TrainingInRotation.deleteOne({ tempUserId: userInfo.tempUserId });
      clearTimeout(timer);
    }, 10000);

    return { errcode: 0, message: '我已经请求成功了!' };
  }

  public async getUserInfo(ctx) {
    const TrainingInRotationUserInfo = await ctx.model.TrainingInRotation.find({ tempUserId: ctx.request.body.tempUserId });
    let res = [];
    if (TrainingInRotationUserInfo.length) {
      const getUserInfo = await ctx.model.User.find({ userId: TrainingInRotationUserInfo[0].userId });
      res = getUserInfo;
    }
    return {
      code: 0,
      data: res,
    };
  }

  public async addUser(ctx) {
    // 验证用户库是否有该用户再进行新增
    const hasUser = await ctx.model.User.find({ userId: ctx.request.body.userId });
    if (hasUser.length) {
      return hasUser;
    }
    const userInfo = {
      ...ctx.request.body,
      registerDate: moment().format('YYYYMMDDHHmmss'),
    };

    const newObj = User.transformerThis(userInfo);
    const validateArr = await newObj.validatorClass(false);

    if (validateArr.length !== 0) {
      return validateArr;
    }

    const res = await ctx.model.User.create(userInfo);
    return res;
  }
}

